package com.huika.dealontop.support.http;

import com.android.volley.NetworkResponse;
import com.android.volley.ParseError;
import com.android.volley.Response;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.HttpHeaderParser;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.hk.app.android.lib.http.FormBaseRequest;
import com.huika.dealontop.utils.DebugTool;

import java.io.UnsupportedEncodingException;
import java.lang.reflect.Type;

public class ObjectResultRequest<T> extends FormBaseRequest<T> {
    private Gson mGson = new GsonBuilder().serializeNulls().create();
    private final Type typeOfT;

    public ObjectResultRequest(String url, Listener<T> listener, ErrorListener errorListener, Type typeOfT) {
        this(Method.POST, url, listener, errorListener, typeOfT);
    }

    public ObjectResultRequest(int method, String url, Listener<T> listener, ErrorListener errorListener, Type typeOfT) {
        super(method, url, listener, errorListener);
        this.typeOfT = typeOfT;
    }

    @Override
    protected Response<T> parseNetworkResponse(NetworkResponse response) {
        try {
            String json = new String(response.data, HttpHeaderParser.parseCharset(response.headers));
            DebugTool.v("http", "ok_json:" + json);
            T ps = mGson.fromJson(json, typeOfT);
            return Response.success(ps, HttpHeaderParser.parseCacheHeaders(response));
        } catch (UnsupportedEncodingException e) {
            return Response.error(new ParseError(e));
        } catch (Exception e) {// 拦截服务器处理异常，判断flag
            try {
                String json = new String(response.data, HttpHeaderParser.parseCharset(response.headers));
                DebugTool.v("http", "error_json:" + json);
                return Response.error(new ServerJsonUnParseError(json));
            } catch (Exception er) {
            }
            return Response.error(new ParseError(e));
        }
    }

    @Override
    public void deliverError(VolleyError error) {
        error.url = getUrl();
        super.deliverError(error);
    }
}
